package com.roncoo.pay.permission.service.impl;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.roncoo.pay.common.core.page.PageBean;
import com.roncoo.pay.common.core.page.PageParam;
import com.roncoo.pay.permission.entity.PmsRole;
import com.roncoo.pay.permission.entity.PmsRolePermission;
import com.roncoo.pay.permission.repository.PmsRolePermissionRepository;
import com.roncoo.pay.permission.repository.PmsRoleRepository;
import com.roncoo.pay.permission.service.PmsRoleService;

/**
 * 角色service接口实现
 *
 */
@Service("pmsRoleService")
public class PmsRoleServiceImpl implements PmsRoleService {
	@Autowired
	private PmsRoleRepository pmsRoleRepository;
	@Autowired
	private PmsRolePermissionRepository pmsRolePermissionRepository;

	/**
	 * 创建pmsOperator
	 */
	public void saveData(PmsRole pmsRole) {
		pmsRoleRepository.save(pmsRole);
	}

	/**
	 * 修改pmsOperator
	 */
	public void updateData(PmsRole pmsRole) {
		pmsRoleRepository.save(pmsRole);
	}

	/**
	 * 根据id获取数据pmsOperator
	 * 
	 * @param id
	 * @return
	 */
	public PmsRole getDataById(String id) {
		return pmsRoleRepository.findOne(id);

	}

	/**
	 * 分页查询pmsOperator
	 * 
	 * @param pageParam
	 * @param ActivityVo
	 *            PmsOperator
	 * @return
	 */
	public PageBean<PmsRole> listPage(PageParam pageParam, PmsRole pmsRole) {
		Example<PmsRole> ex = Example.of(pmsRole);
		
		Pageable pg = new PageRequest(pageParam.getPageNum(), pageParam.getNumPerPage());
		
		Page<PmsRole> page = pmsRoleRepository.findAll(ex, pg);
		
		PageBean<PmsRole> pb = new PageBean<PmsRole>(pageParam.getPageNum(), pageParam.getNumPerPage(), page.getTotalPages(),page.getContent());
		return pb;
	}

	/**
	 * 获取所有角色列表，以供添加操作员时选择.
	 * 
	 * @return roleList .
	 */
	public List<PmsRole> listAllRole() {
		return pmsRoleRepository.findAll();
	}

	/**
	 * 判断此权限是否关联有角色
	 * 
	 * @param permissionId
	 * @return
	 */
	public List<PmsRole> listByPermissionId(String permissionId) {
		Set<PmsRole> roleSets = Sets.newHashSet();
		List<PmsRolePermission> list = pmsRolePermissionRepository.findByPermissionId(permissionId);
		for(PmsRolePermission rolePermission : list){
			roleSets.add(pmsRoleRepository.findOne(rolePermission.getRoleId()));
		}
		return Lists.newArrayList(roleSets);
	}

	/**
	 * 根据角色名或者角色编号查询角色
	 * 
	 * @param roleName
	 * @param roleCode
	 * @return
	 */
	public PmsRole getByRoleNameOrRoleCode(String roleName, String roleCode) {
		return pmsRoleRepository.findByRoleNameOrRoleCode(roleName, roleCode);
	}

	/**
	 * 删除
	 * 
	 * @param roleId
	 */
	public void delete(String roleId) {
		pmsRoleRepository.delete(roleId);
	}
}
